import Vue from 'vue'
import Vuex from 'vuex'
import QQMapWX from '../lib/qqmap-wx-jssdk.js'
Vue.use(Vuex)
const store=new Vuex.Store({
	state:{
		userInfo:uni.getStorageSync('userInfo') || '',
		openId:null,
		adName:uni.getStorageSync('adName') || '',
		adCode:uni.getStorageSync('adCode') || '',
		cityList:[],
	},
	mutations:{
		SET_CITY(state,val){
			uni.setStorageSync('adName',val.adName)
			uni.setStorageSync('adCame',val.adCode)
			state.adName=val.adName
			state.adCode=val.adCode
		}
	},
	actions:{
		// 改变位置
		changeCity({commit},val){
			commit('SET_CITY',val)
		},
		// 获取当前位置
		getCity({commit}){
			return new Promise((resolve,reject)=>{
				let latitude
				let longitude
				const tMap = new QQMapWX({
					key: 'JSCBZ-QHRWD-DZD4B-PUZQ7-DUM5O-2NFQ2' //开发者密钥
				});
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					success: (res) => {
						latitude = res.latitude;
						longitude = res.longitude;
					},
					complete: () => {
						tMap.reverseGeocoder({
							location: {
								latitude,
								longitude
							},
							success: res => {
								let adName=res.result.address_component.city
								let adCode=res.result.ad_info.adcode && res.result.ad_info.adcode.substr(0,4)
								commit('SET_CITY',{adName,adCode})
								resolve({adName,adCode})
							},
						})
					}
				})
			})
		}
	}
})
export default store